package reportchart.object;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.RectangleEdge;

public class PieChart extends JPanel {

    private static int total = 0;
    private static String nameFile;
    private static String selectedPath;
    private static PieChart instance = new PieChart();
    private static String time;

    /**
     * @return the time
     */
    public static String getTime() {
        return time;
    }

    /**
     * @param aTime the time to set
     */
    public static void setTime(String aTime) {
        time = aTime;
    }
    // data pie chart
    private Map<String, Integer> dataVersion = new TreeMap<String, Integer>();

    public PieChart(String selectedPath, String nameFile) {
        this.selectedPath = selectedPath;
        this.nameFile = nameFile;
    }

    public PieChart() {
    }

    /**
     * @return the dataVersion
     */
    public Map<String, Integer> getDataVersion() {
        return dataVersion;
    }

    /**
     * @param aDataVersion the dataVersion to set
     */
    public void setDataVersion(Map<String, Integer> aDataVersion) {
        dataVersion = aDataVersion;
    }

    /**
     * @return the selectedPath
     */
    public static String getSelectedPath() {
        return selectedPath;
    }

    /**
     * @param aSelectedPath the selectedPath to set
     */
    public static void setSelectedPath(String aSelectedPath) {
        selectedPath = aSelectedPath;
    }

    /**
     * @return the total
     */
    public static int getTotal() {
        return total;
    }

    /**
     * @param total the total to set
     */
    public void setTotal(int total) {
        this.total = total;
    }

    /**
     * @return the nameFile
     */
    public static String getNameFile() {
        return nameFile;
    }

    /**
     * @param nameFile the nameFile to set
     */
    public void setNameFile(String nameFile) {
        this.nameFile = nameFile;
    }

    /**
     *  create data to draw
     * @return dataset
     */
    public static PieDataset createDataset(Map<String, Integer> dataVersion) {
        DefaultPieDataset dataset = new DefaultPieDataset();

        //read file to get data
        if (dataVersion == null) {
            JFrame frame = new JFrame("Warning");
            JOptionPane.showMessageDialog(frame,
                    " You can't show chart! Please click File/Open...!",
                    "Warning", JOptionPane.WARNING_MESSAGE);
        } else {
            for (Entry<String, Integer> entry : dataVersion.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();

                dataset.setValue(key, value);
            }
        }

        return dataset;
    }

    /**
     * Create chart 
     * @param dataset
     * @return a chart
     */
    public static JFreeChart createChart(PieDataset dataset) {
        JFreeChart chart = ChartFactory.createPieChart("Thống kê version iWin trên từng server \n"
                + "Ngày: " + getTime() + "\n"
                + "Tống số lượng các version được sử dụng: " + getTotal(), dataset,
                true, true, false);
        chart.setBackgroundPaint(Color.white);

        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setSectionOutlinesVisible(true);
        plot.setIgnoreZeroValues(true);
        plot.setIgnoreNullValues(true);
        plot.setCircular(true);
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

        plot.setNoDataMessage("No data available");
//        plot.setInteriorGap(0.05);
        plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("Version {0} = {1}", NumberFormat.getNumberInstance(), NumberFormat.getIntegerInstance()));
        LegendTitle title = chart.getLegend();
        title.setPosition(RectangleEdge.LEFT);
        return chart;
    }

    /**
     * create a panel chart
     * @return a panel
     */
    public static JPanel createPanel(Map<String, Integer> dataVersion) {
        PieDataset dataset = createDataset(dataVersion);

        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 600));
        chartPanel.setMouseZoomable(true, false);
        try {
            saveToFile(chart, "C:/Users/PCLT/Documents/Server 1/Version/" + getNameFile() + ".jpg", 1460, 768, 200);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chartPanel;
    }

    /**
     * @return the instance
     */
    public static PieChart getInstance() {
        if (instance == null) {
            instance = new PieChart();
        }
        return instance;
    }

    public static void saveToFile(JFreeChart chart,
            String aFileName,
            int width,
            int height,
            double quality)
            throws FileNotFoundException, IOException {

        BufferedImage img = draw(chart, width, height);



        FileOutputStream fos = new FileOutputStream(aFileName);

        JPEGImageEncoder encoder2 =
                JPEGCodec.createJPEGEncoder(fos);

        JPEGEncodeParam param2 =
                encoder2.getDefaultJPEGEncodeParam(img);

        param2.setQuality((float) quality, true);

        encoder2.encode(img, param2);

        fos.close();

    }

    protected static BufferedImage draw(JFreeChart chart, int width, int height) {

        BufferedImage img =
                new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = img.createGraphics();



        chart.draw(g2, new Rectangle2D.Double(0, 0, width, height));



        g2.dispose();

        return img;

    }
}
